package mfgrep;

import java.io.File;
import java.util.logging.Logger;

/**
 * Dir Walker. Dedicated to Johnny Walker :-)
 * 
 * Walks down the directory tree.
 * 
 * Class is NOT thread safe!
 * 
 * @author lzapletal
 */
public class DirWalker {

		private static Logger logger = Logger.getAnonymousLogger();
		
		private Grepper grepper;

		private File rootDir;
				private ProgramOptions programOptions;

		public DirWalker(File rootDir, Grepper grepper, ProgramOptions programOptions) {
				if (rootDir == null || !rootDir.isDirectory()) 
						throw new IllegalArgumentException("Root entry must be not null and valid directory");
				if (programOptions == null) 
						throw new IllegalArgumentException("Program options cannot be null");
				if (grepper == null) 
						throw new IllegalArgumentException("Grepper instance cannot be null");
				this.rootDir = rootDir;
				this.programOptions = programOptions;
				this.grepper = grepper;
		}

		void walk() throws ProcessingException {
				walk(rootDir);
		}
		
		void walk(File root) throws ProcessingException {
				File[] list = root.listFiles();
				for (File file: list) {
						if (file.isDirectory()) {
								if (file.canExecute() && file.canRead()) {
										walk(file);
								} else {
										logger.warning("Cannot read directory " + file);
								}
						} else if (file.isFile()) {
								grepper.acceptFile(file);
						}
				}
		}
}